package com.coolyu.lab.server;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class YtDownloader
 */
public class YtDownloader extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public static Map<String,String> URLMap = new HashMap<String,String>();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public YtDownloader() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getParameter("videoId")!=null){
			getFlv(request,response);
		}
		else if(request.getParameter("flv")!=null){
			returnFlvFile(request,response);
		}
		else{
			response.getOutputStream().println("You forget to put parameter!!");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public void getFlv(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String s = URLMap.get("viedoId");
		if(s!=null){
			response.getOutputStream().println(s);
			return;
		}
		
		String message = URLEncoder.encode("http://www.youtube.com/watch?v=" + request.getParameter("videoId"), "UTF-8");

        try {
            URL url = new URL("http://kej.tw/flvretriever/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("videoUrl=" + message);
            writer.close();
            InputStreamReader in = new InputStreamReader(connection.getInputStream());
        	BufferedReader bin = new BufferedReader(in);
   
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
            	
            	String tmp = "";
            	String body = "";
            	
            	//response.getWriter().println(bin.readLine());
            	while((tmp=bin.readLine())!=null){
            		body+=tmp;
            	}
            	//response.getWriter().println(body);
            	int beginIndex = body.indexOf("id=\"outputfield\">") + 17;
            	int endIndex = body.indexOf("</textarea>");
            	String flv = body.substring(beginIndex, endIndex);
            	response.getWriter().println(flv);
            	URLMap.put(request.getParameter("videoId"), flv);
            	//System.out.println(flv);
            	
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
	}
	public void returnFlvFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//response.getOutputStream().println(URLMap.get(request.getParameter("flv")));
		
		URL url = new URL(URLMap.get(request.getParameter("flv")));
		System.out.println(URLMap.get(request.getParameter("flv")));
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.connect();
            response.setContentType("video/x-flv");
            //BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
            System.out.println("a");

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                
                byte[] buffer = new byte[1];
                System.out.println("start");
                while(in.read(buffer)!=-1){
                	out.write(buffer);
                }
            	in.close();
            	out.close();
            	System.out.println("finished");
            	byte[] b = new byte[1];
            	ByteArrayInputStream bin = new ByteArrayInputStream(out.toByteArray());
            	BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());
            	while(bin.read(b)!=-1){
            		bout.write(b);
            	}
            } else {
                // Server returned HTTP error code.
            	System.out.println("error");
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
		
	}
}
